package com.example.hfweather.ui.home

import android.content.Context
import android.widget.Toast
import com.example.hfweather.R
import com.example.hfweather.base.BasePresenter
import com.example.hfweather.bean.ChangeCityBean
import com.google.common.reflect.TypeToken
import com.google.gson.Gson
import com.qweather.sdk.response.air.v1.AirV1CurrentResponse
import com.qweather.sdk.response.air.v1.AirV1HourlyResponse
import com.qweather.sdk.response.geo.GeoCityTopResponse
import com.qweather.sdk.response.weather.WeatherHourlyResponse
import com.qweather.sdk.response.weather.WeatherNowResponse

class HomePresenter(val mView: HomeView, val mInteractor: HomeInteractor) :
    BasePresenter<HomeView, HomeInteractor>(mView, mInteractor), HomeInteractor.GetMainWeatherData,
    HomeInteractor.GetHourlyWeatherData, HomeInteractor.GetHourlyAirQualityData,
    HomeInteractor.GetCurrentAirQualityData, HomeInteractor.GetTopCityListData {


    private var currShowCityName = ""
    private var currShowLatitude = ""
    private var currShowLongitude = ""

    fun getCurrShowCityName(): String {
        return currShowCityName
    }
    fun getCurrShowLatitude(): String {
        return currShowLatitude
    }
    fun getCurrShowLongitude(): String {
        return currShowLongitude
    }

    private var cityList = arrayListOf<ChangeCityBean>()

    fun requestTopCityListData() {
        mInteractor.getCityList(this)
    }

    /**
     *  设置当前展示的城市名和经纬度数据
     */
    fun setCityLocationParams(cityName: String, latitude: String, longitude: String) {
        currShowCityName = cityName
        currShowLatitude = latitude
        currShowLongitude = longitude
    }

    fun requestMainWeatherData() {
//        mView.showLoading()
        mInteractor.getCityCurrentWeather(currShowLatitude, currShowLongitude, this)
        mInteractor.getCityHourlyWeather(currShowLatitude, currShowLongitude, this)
        mInteractor.getCityAirQuality(currShowLatitude, currShowLongitude, this)
        mInteractor.getCityCurrentAirQuality(currShowLatitude, currShowLongitude, this)
    }


    override fun getWeatherDataSuccess(response: WeatherNowResponse) {
        mView.getMainWeatherDataSuccess(response)
    }

    override fun getWeatherDataFailed(message: String) {
        mView.getMainWeatherDataFailed(message)
    }

    override fun getHourlyWeatherDataSuccess(response: WeatherHourlyResponse) {
        mView.getHourlyWeatherDataSuccess(response)
    }

    override fun getHourlyWeatherDataFailure(errorResponse: String) {
        mView.getHourlyWeatherDataFailure(errorResponse)
    }

    override fun getHourlyAirQualityDataSuccess(response: AirV1HourlyResponse) {
        mView.getAirQualityDataSuccess(response)
    }

    override fun getHourlyAirQualityDataFailure(errorResponse: String) {
        mView.getAirQualityDataFailure(errorResponse)
    }

    override fun getCurrentAirQualityDataSuccess(response: AirV1CurrentResponse) {
        mView.getCurrentAirQualityDataSuccess(response)
    }

    override fun getCurrentAirQualityDataFailure(errorResponse: String) {
        mView.getCurrentAirQualityDataFailure(errorResponse)
    }

    override fun getTopCityDataSuccess(response: GeoCityTopResponse) {
        cityList.clear()
        //1.要把当前展示的城市放到最前面
        val currentBean = ChangeCityBean(
            currShowCityName, currShowLatitude.toDouble(), currShowLongitude.toDouble(), true
        )
        cityList.add(currentBean)
        //2.从本地获取json文件内容
        val cityListFromRaw = readCitiesFromRaw(mView.getContext()!!, R.raw.city_list)

        cityListFromRaw.forEach {
            if (it.cityName != currShowCityName) {
                cityList.add(
                    ChangeCityBean(
                        it.cityName, (it.latitude).toDouble(), (it.longitude).toDouble(), false
                    )
                )
            }
        }

        //这里的数据返回城市/区划都有，数据不够纯净。以及 本地位置和其他城市、区划的排序，正常情况下是服务器处理好，返回给前端
        //和风天气给的城市数据太混乱了，这里不好处理，我们直接拿官方提供的一些城市数据放本地做展示好了
        //        response.topCityList?.forEach {
        //
        //        }
        //刷新列表
        mView.refreshCityCityList(cityList)
    }

    /**
     * 读取raw中的城市数据
     */
    fun readCitiesFromRaw(context: Context, resId: Int): List<ChangeCityBean> {
        return try {
            // 打开指定的raw资源文件并读取为字符串
            val jsonString =
                context.resources.openRawResource(resId).bufferedReader().use { it.readText() }

            // 使用TypeToken定义目标类型，用于Gson解析泛型List<ChangeCityBean>
            val type = object : TypeToken<List<ChangeCityBean>>() {}.type

            // 使用Gson将JSON字符串转换为List<ChangeCityBean>对象
            Gson().fromJson(jsonString, type)
        } catch (e: Exception) {
            e.printStackTrace()
            emptyList()
        }
    }

    override fun getTopCityDataFailure(errorResponse: String) {
        Toast.makeText(mView.getContext(), "获取其他城市失败", Toast.LENGTH_SHORT).show()
    }
}